import { FunctionComponent, useEffect, useState } from 'react';
import styles from './Trash.module.scss';
import { Empty, Table, Tag, Space, Button, Spin, message } from 'antd';
import type { ColumnsType } from 'antd/es/table';
import ListSearch from '../../../components/listSearch/ListSearch';
import useLoadQuestionList from '../../../hooks/requestHooks/useLoadQuestionList';
import ListPagination from '../../../components/pagination/Pagination';
import { useRequest } from 'ahooks';
import { updateQuestion } from '../../../api/question';
interface TrashProps {
  [key: string]: any;
}

interface DataType {
  id: string;
  title: string;
  isStar: boolean;
  isPublished: boolean;
  answerCount: number;
  createAt: string;
}

const Trash: FunctionComponent<TrashProps> = () => {
  const [selectId, setSelectId] = useState<(number | string)[]>([]);

  const colums: ColumnsType<DataType> = [
    { title: '标题', dataIndex: 'title', key: 'title' },
    {
      title: '收藏',
      dataIndex: 'isStar',
      key: 'isStar',
      render: isStar =>
        isStar ? <Tag color="processing">已收藏</Tag> : <Tag>未收藏</Tag>,
    },
    {
      title: '出版',
      dataIndex: 'isPublished',
      key: 'isPublished',
      render: isPublished =>
        isPublished ? <Tag color="processing">已发布</Tag> : <Tag>未发布</Tag>,
    },
    { title: '回答数', dataIndex: 'answerCount', key: 'answerCount' },
    { title: '创建日期', dataIndex: 'createAt', key: 'createAt' },
    {
      title: '操作',
      key: 'action',
      render: (_, record) => {
        return (
          <>
            <Space>
              <Button
                type="primary"
                onClick={() => restoreQuestion(record.id)}
                loading={restoreLoading}
              >
                恢复
              </Button>
              <Button
                type="primary"
                onClick={() =>
                  setQuestionList(
                    questionList.filter(item => item.id != record.id),
                  )
                }
              >
                删除{record.title}
              </Button>
            </Space>
          </>
        );
      },
    },
  ];

  const [questionList, setQuestionList] = useState<DataType[]>([]);

  const {
    data = {},
    loading,
    refresh,
  } = useLoadQuestionList({ isDeleted: true });
  useEffect(() => {
    if (data?.data) {
      setQuestionList(data.data);
    }
  }, [data]);

  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[], selectedRows: DataType[]) => {
      setSelectId(selectedRowKeys);
    },
    getCheckboxProps: (record: DataType) => ({
      disabled: record.title === '问卷1', // Column configuration not to be checked
      name: record.title,
    }),
  };

  //处理批量删除
  const hanlderDeleteBySelect = () => {
    selectId.forEach(selectId => {
      //!!!!!!!!!!!!!!!!!!!这种方法会导致无法批量删除，因为setstate合并了，应该使用回调函数的方式
      // const newQuestionList = questionList.filter(item=>item.id != selectId)
      // console.log(newQuestionList)
      // setQuestionList(newQuestionList)

      //基于上一次的结果来修改数据  修改其原始数据并且在循环时修改，需要使用这种方式。
      setQuestionList(prev => {
        const newQuestionList = prev.filter(item => item.id != selectId);
        return newQuestionList;
      });
    });
  };

  //单体恢复于批量恢复
  const { loading: restoreLoading, runAsync: restore } = useRequest(
    updateQuestion,
    {
      manual: true,
    },
  );
  const restoreQuestion = (
    id?: string | React.MouseEventHandler<HTMLElement>,
  ) => {
    if (typeof id == 'number') {
      console.log(2);
      restore(id, { isDeleted: false }).then(() => {
        setQuestionList(questionList.filter(item => item.id != id));

        message.success('恢复成功');
      });
    } else {
      restore(selectId, { isDeleted: false }).then(() => {
        const newData = questionList.filter(
          item => !selectId.some(sid => sid === item.id),
        );
        setQuestionList(newData);
        setSelectId([]);
        message.success('批量恢复成功');
        // refresh();
      });
    }
  };

  return (
    <>
      <div className={styles.container}>
        <div className={styles.header}>
          <div className={styles.left}>
            <h3>回收站</h3>
          </div>
          <div className={styles.right}>
            <ListSearch />
          </div>
        </div>
        <Space>
          <Button
            onClick={hanlderDeleteBySelect}
            type="default"
            danger
            disabled={!selectId.length}
          >
            批量删除
          </Button>
          <Button
            onClick={restoreQuestion}
            disabled={!selectId.length}
            type="default"
            loading={restoreLoading}
          >
            恢复
          </Button>
        </Space>
        <div>
          {loading && (
            <div style={{ textAlign: 'center' }}>
              <Spin />
            </div>
          )}
          {questionList.length > 0 && (
            <Table
              rowSelection={{ type: 'checkbox', ...rowSelection }}
              columns={colums}
              dataSource={questionList}
              rowKey="id"
            />
          )}
          {!loading && data?.data?.length === 0 && (
            <Empty description="暂无数据" />
          )}
        </div>
        {!loading && data?.data?.length > 0 && (
          <ListPagination total={data.total} />
        )}
      </div>
    </>
  );
};

export default Trash;
